using System;
using System.Collections.Generic;
using System.Reflection;
namespace ServiceStack.Messaging
{
	public static class MessageFactory
	{
		private static readonly Dictionary<Type, MessageFactoryDelegate> CacheFn = new Dictionary<Type, MessageFactoryDelegate>();
		public static IMessage Create(object response)
		{
			if (response == null)
			{
				return null;
			}
			Type type = response.GetType();
			Dictionary<Type, MessageFactoryDelegate> cacheFn = MessageFactory.CacheFn;
			MessageFactoryDelegate messageFactoryDelegate;
			lock (cacheFn)
			{
				MessageFactory.CacheFn.TryGetValue(type, ref messageFactoryDelegate);
			}
			if (messageFactoryDelegate != null)
			{
				return messageFactoryDelegate(response);
			}
			MethodInfo method = typeof(Message<>).MakeGenericType(new Type[]
			{
				type
			}).GetMethod("Create", 24);
			messageFactoryDelegate = (MessageFactoryDelegate)Delegate.CreateDelegate(typeof(MessageFactoryDelegate), method);
			cacheFn = MessageFactory.CacheFn;
			lock (cacheFn)
			{
				MessageFactory.CacheFn.set_Item(type, messageFactoryDelegate);
			}
			return messageFactoryDelegate(response);
		}
	}
}
